import React, { useState } from 'react';
import { Table, Button, Modal, Form, Input, message, Select } from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';

interface Edge {
  source: string;
  target: string;
  condition?: string;
}

interface Node {
  id: string;
  name: string;
}

interface EdgeEditorProps {
  edges: Edge[];
  nodes: Node[];
  onChange: (edges: Edge[]) => void;
}

const EdgeEditor: React.FC<EdgeEditorProps> = ({ edges, nodes, onChange }) => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingEdge, setEditingEdge] = useState<Edge | null>(null);
  const [form] = Form.useForm();

  const handleEdit = (edge: Edge) => {
    setEditingEdge(edge);
    form.setFieldsValue(edge);
    setIsModalVisible(true);
  };

  const handleDelete = (edge: Edge) => {
    const newEdges = edges.filter(
      e => !(e.source === edge.source && e.target === edge.target)
    );
    onChange(newEdges);
    message.success('边删除成功');
  };

  const handleSave = () => {
    form.validateFields().then(values => {
      const newEdge: Edge = {
        source: values.source,
        target: values.target,
        condition: values.condition,
      };

      if (editingEdge) {
        const newEdges = edges.map(edge =>
          edge.source === editingEdge.source && edge.target === editingEdge.target
            ? newEdge
            : edge
        );
        onChange(newEdges);
      } else {
        onChange([...edges, newEdge]);
      }

      setIsModalVisible(false);
      message.success('边保存成功');
    });
  };

  const columns = [
    {
      title: '源节点',
      dataIndex: 'source',
      key: 'source',
      render: (source: string) => {
        const node = nodes.find(n => n.id === source);
        return node ? node.name : source;
      },
    },
    {
      title: '目标节点',
      dataIndex: 'target',
      key: 'target',
      render: (target: string) => {
        const node = nodes.find(n => n.id === target);
        return node ? node.name : target;
      },
    },
    {
      title: '条件',
      dataIndex: 'condition',
      key: 'condition',
      render: (condition?: string) => condition || '无条件',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Edge) => (
        <span>
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          />
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          />
        </span>
      ),
    },
  ];

  return (
    <div>
      <Table
        columns={columns}
        dataSource={edges}
        rowKey={(record) => `${record.source}-${record.target}`}
        pagination={false}
        locale={{ emptyText: '暂无数据' }}
      />

      <Modal
        title={editingEdge ? '编辑边' : '添加边'}
        open={isModalVisible}
        onOk={handleSave}
        onCancel={() => setIsModalVisible(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="source"
            label="源节点"
            rules={[{ required: true, message: '请选择源节点' }]}
          >
            <Select placeholder="请选择源节点">
              {nodes.map(node => (
                <Select.Option key={node.id} value={node.id}>
                  {node.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="target"
            label="目标节点"
            rules={[{ required: true, message: '请选择目标节点' }]}
          >
            <Select placeholder="请选择目标节点">
              {nodes.map(node => (
                <Select.Option key={node.id} value={node.id}>
                  {node.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="condition"
            label="条件表达式"
            tooltip="用于条件节点的分支判断，支持JavaScript表达式"
          >
            <Input.TextArea
              placeholder="请输入条件表达式，例如：data.value > 100"
              rows={3}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default EdgeEditor;